﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Framework.Platform.Components.UI.Presenter;

namespace Framework.Platform.Components.UI.View
{
    public partial class SimpleTreeNavigator : BaseNavigator
    {
        public SimpleTreeNavigator()
        {
            InitializeComponent();
        }

        private IDictionary<string, TreeNode> _Nodes = new Dictionary<string, TreeNode>();

        #region INavigator Members
        public override void SelectItemByKey(string key)
        {
            foreach (string nodeKey in this._Nodes.Keys)
            {
                if (key == nodeKey)
                {
                    this.tv_NavigatorTree.SelectedNode = this._Nodes[key];
                }
            }
        }

        public override void AddItem(NavigatorItemBase item)
        {
            TreeNode node = new TreeNode();
            node.Text = item.Text;
            node.Tag = item;
            if (string.IsNullOrEmpty(item.ParentKey))
            {
                this.tv_NavigatorTree.Nodes.Add(node);
                _Nodes.Add(item.Key, node);
            }
            else
            {
                if (!_Nodes.ContainsKey(item.ParentKey))
                {
                    _Nodes[item.ParentKey].Nodes.Add(node);
                }
            }

        }

        public override void RemoveItem(string itemKey)
        {
            if (this._Nodes.ContainsKey(itemKey))
            {
                this.tv_NavigatorTree.Nodes.Remove(this._Nodes[itemKey]);
                this._Nodes.Remove(itemKey);
            }
        }

        public override NavigatorItemBase GetItemByKey(string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                return null;
            }
            if (_Nodes.ContainsKey(key))
            {
                return (NavigatorItemBase)_Nodes[key].Tag;
            }
            else
            {
                return null;
            }
            
        }
        #endregion

        private void tv_NavigatorTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            NavigatorItemBase newItem = e.Node.Tag as NavigatorItemBase;
            if (newItem != null)
            {
                if (!(this.SelectedItem != null && this.SelectedItem.Key == newItem.Key))
                {
                    NavigatorSelectedChangedEventArgs arg = new NavigatorSelectedChangedEventArgs();
                    arg.OldItem = SelectedItem;
                    arg.NewItem = newItem;
                    arg.ViewEventKey = NavigatorEvents.OnSelectedChanged;
                    this.OnViewEventRaise(arg);
                }
            }
            this.SelectedItem = newItem;
        }
    }
}